const form = document.getElementById('form');
const username = document.getElementById('username');
const email = document.getElementById('email');
const password = document.getElementById('password');
const password2 = document.getElementById('password2');

// 显示错误提示信息
function showError(input, message) {
    // 获取输入框的父元素
    const formControl = input.parentElement;
    console.log();
    formControl.className = 'form-control error';
    // 提示信息
    const small = formControl.querySelector('small');
    small.innerText = message;
}

// 验证无误
function showSuccess(input) {
    // 获取输入框的父元素
    const formControl = input.parentElement;
    formControl.className = 'form-control success';
}

// 邮箱校验
function checkEmail(input) {
    const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    // 去除空格
    if (re.test(input.value.trim())) {
        showSuccess(input)
    } else {
        showError(input,'Email is not valid')
    }
}

// 必须字段非空校验
function checkRequired(inputArray) {
    let isRequired = false;
    inputArray.forEach(function (input) {
        if (input.value.trim() === '') {
            showError(input, `${getFieldName(input)} is required`);
            isRequired = true;
        } else {
            showSuccess(input)
        }
    })

    return isRequired;
}

// 长度检查
function checkLength(input, min, max) {
    if (input.value.length < min) {
        showError(input, `${getFieldName(input)} must be at least ${min} characters`)
    } else if (input.value.length > max) {
        `${getFieldName(input)} must be at less ${max} characters`
    }else {
        showSuccess(input)
    }
}

// 密码匹配验证
function checkPasswordMatch(input1,input2) {
    if(input1.value!==input2.value) {
        showError(input2,'Password do not Match');
    }
}

// 获取字段名
function getFieldName(input) {
    return input.id.charAt(0).toUpperCase()+input.id.slice(1)
}

// 事件监听
form.addEventListener('click',function(e){
    // 阻止默认事件
    e.preventDefault();
    // 进行非空校验
    if(checkRequired([username,email,password,password2])) {
        // 长度检查
        checkLength(username,3,15);
        checkLength(password,6,25);
        // 邮箱格式检查
        checkEmail(email);
        // 密码匹配
        checkPasswordMatch(password,password2)
    }
})